package com.ly.consumer.thread.threadCreatMethod;

import com.common.core.utils.ThreadPoolUtil;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
//创建线程 各个线程之间有返回值的
class MyCallable implements Callable<Integer> {
    private String name;
    public MyCallable(String name) {
        this.name = name;
    }
    @Override
    public Integer call() throws Exception {
        Thread.sleep(200);
        int sum = 0;
        int random = (int)(Math.random()*10);
        System.out.println(name+"：产生了一个随机数："+random);
        for (int i = 0; i <=random ; i++) {
            sum+=i;
        }
        return sum;
    }
}
public class MyCallableDemo {
    public static void main(String[] args) {
        //使用线程池创建线程
        ThreadPoolExecutor threadPoolExecutor = ThreadPoolUtil.getThreadPoolExecutorCPU();
        MyCallable myCallable1 = new MyCallable("线程1");
        MyCallable myCallable2 = new MyCallable("线程2");
        MyCallable myCallable3 = new MyCallable("线程3");
        Future<Integer> result1 = threadPoolExecutor.submit(myCallable1);
        Future<Integer> result2 =threadPoolExecutor.submit(myCallable2);
        Future<Integer> result3 =threadPoolExecutor.submit(myCallable3);
        //关闭线程池
//        threadPoolExecutor.shutdown();
        try {
            System.out.println("线程1："+result1.get());
            System.out.println("线程2："+result2.get());
            System.out.println("线程3："+result3.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
